var Socket = {
  ready: false,
  socket: null,

  connectServer: function() {
    var socketPort = 6600;
    var socketServer = 'http://' + location.hostname + ':' + socketPort;
    this.socket = io.connect(socketServer);
  },
  
  registerEvent: function() {
    var socket = this.socket;

    // Handle throw action from client.
    socket.on('throw_response', function (data) {
      if (Chess.ready) {
        $.log('throw_response listeners, data: ' + JSON.stringify(data));
        var name = data.name;
        var result = data.result;
        var player = Chess.getPlayer(name);
        Chess.currentPlayer = player;
        Chess.throwDice(player, result);
      }
    });

    socket.on('login', function(who) {
      if (Chess.ready) {
        $.log('login listener, who: ' + who);
        UI.setPlayerReady(who);
        Chess.addPlayer(who);
      }
    });

    socket.on('game_start', function(data) {
      if (Chess.ready) {
        $.log('game_start listener, data: ' + JSON.stringify(data));
        var startBy = data.startBy;
        Chess.startGame(startBy);
      }
    });

    socket.on('remove_player', function(name) {
      if (Chess.ready) {
        Chess.removePlayer(name);
        UI.resetPlayerReadyStatus(name);
      }
    });

    socket.on('stop_game', function(name) {
      Chess.handleStopGame(name);
    });

    socket.on('disconnect', function() {
      console.log('disconnect');
      Chess.ready = false;
    });
  },

  registerView: function() {
    this.socket.emit('view_ready', 'view', function() {
      $.log('view ready.');
      Chess.ready = true;
    });
  },

  requestThrowDice: function(playerName) {
    if (Chess.ready) {
      $.log('request throw to player ' + playerName);
      this.socket.emit('throw_request', playerName);
    }
  },

  endGame: function(playerName) {
    if (Chess.ready) {
      this.socket.emit('game_end', {
        winner: playerName
      });
    }
  }
};